# -*- coding: utf-8 -*-
import json
import os
from pyquery import PyQuery
from requests.exceptions import ConnectionError
from export.distributors.b2b import B2b
from export.models import BaseProduct_B2b as Product_B2b, \
    BaseProduct_Stock as Product_Stock
from settings import STATICFILES_DIRS


class Ugcontract(B2b):
    host = 'http://yugcontract.ua/'
    mainUrl = 'http://wholesale.yugcontract.ua/'
    loginUrl = 'http://wholesale.yugcontract.ua/wholesale/main.html'
    categoryUrl = 'wholesale/tree/?parent_id='

    stocksName = [['availability', 'Склад Киев'], ['availability_r2_0', 'Склад Винница']]
    stock = {}
    catalog = {}

    username = 'KHazin_Marat'
    userpass = 'nm*@Za'

    def __init__(self):
        B2b.__init__(self)
        self.login()
        self.setCurrency()

    def getStockbyName(self, stockName):
        stock = Product_Stock.objects.get_or_create(stock_name=stockName, b2b=self.getUgcontract())
        return stock[0]

    def getProductsListUrl(self, categoryId):
        return 'wholesale/list/%s/fac-n/fpt-n/fsr-n/fst-n/fwh-n/l10000/sdir-desc/sort-model/?prop=0' % categoryId

    def getSearchProductUrl(self, query):
        return 'wholesale/list/search/l10000/sdir-desc/sort-model/?q=' + query

    def getUgcontract(self):
        b2b = Product_B2b.objects.get_or_create(b2b='ug-contract')
        return b2b[0]

    def setCurrency(self):
        self.browser.open(self.mainUrl)
        #        some time
        self.currency = 8.20

    def searchBySitePage(self, query, categoryName):
        result = json.loads(self.browser.open("%s%s" % (self.mainUrl, self.getSearchProductUrl(query))).get_data())
        if len(result['products']) == 1:
            return self.handlerHtmlProduct(result['products'][0], categoryName)
        return False

    def isLogin(self, page):
        return self.mainUrl == page

    def setCategory(self, categoryId='0'):
        products = []
        categories = json.loads(self.browser.open(self.mainUrl + self.categoryUrl + categoryId).get_data(),
                                encoding='utf-8')
        for category in categories:
            if categoryId == '0':
                self.setCategory(category['id'])
            elif not category['have_children']:
                products += self.handlerHtmlCategory(category['id'], category['name'])
            elif str(category['id']).find(categoryId) != -1 and int(category['level']) == categoryId.count('_') + 1:
                self.setCategory(category['id'])
        return products

    def login(self):
        try:
            self.browser.open(self.mainUrl)
            if self.isLogin(self.browser.geturl()):
                return True
            self.browser.select_form(nr=0)
            self.browser['user_login'] = self.username
            self.browser['user_password'] = self.userpass
            self.browser.submit()
            if self.isLogin(self.browser.geturl()):
                return True
            else:
                return False
        except ConnectionError:
            return False

    def parsing(self):
        self.setCategory()

    def handlerHtmlCatalog(self, **kwargs):
        products = []
        definiteCategoryName = kwargs['definiteCategoryName']
        categories = json.loads(self.browser.open(self.mainUrl + self.categoryUrl + '0').get_data(),
                                encoding='utf-8')
        for category in categories:
            if category['name'] == definiteCategoryName:
                products += self.proccessRule(
                    {definiteCategoryName: self.handlerHtmlCategory(category['id'], category['name'])})
        return products

    def handlerHtmlCategory(self, categoryId, categoryName):
        products = []
        products_ = json.loads(self.browser.open(self.mainUrl + self.getProductsListUrl(categoryId)).get_data(),
                               encoding='utf-8')
        for product in products_['products']:
            product = self.handlerHtmlProduct(product, categoryName)
            if product:
                products.append(product)
        return products

    def handlerHtmlProduct(self, _product, categoryName):
        product = {'brand_name': _product['brand'], 'name': _product['name'],
                   'descr': _product['descr_typhoon'], 'sku': _product['artikul']}
        if not self.checkProduct(product['sku'], 1):
            return None
        product['price'] = self.getProductPriceBySKu(product['sku'])
        if not _product['descr_url']:
            return None
        product.update(self.handlerHtmlProductAttribute(_product['descr_url']))
        return product

    def saveImage(self, productSku, listImage):
        for imageTag in listImage:
            self.browser.retrieve(self.host + imageTag.attrib['href'], os.path.join(STATICFILES_DIRS[0],
                                                                                    'images/%s_%s.jpg' % (productSku,
                                                                                                          listImage.index(
                                                                                                              imageTag))))

    def handlerHtmlProductAttribute(self, link):
        product = {}
        jQuery = PyQuery(self.browser.open(link).get_data())
        product['short_descr'] = jQuery('.item-descr-small-content')[0].text_content().replace('\n', '').strip()
        prop = jQuery('.prop')
        value = jQuery('.val')
        attrs = {}
        if len(prop) == len(value):
            for i in range(len(prop)):
                attrs[prop[i].text.replace('\n', '').strip()] = value[i].text_content().replace('\n', '').strip()
        product['attrs'] = attrs
        return product
